package com.zee.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zee.admin.dao.SysMenuDao;
import com.zee.admin.entity.SysMenu;
import com.zee.admin.enums.SuperAdminEnum;
import com.zee.admin.model.dto.SysMenuDTO;
import com.zee.admin.model.response.AdminCode;
import com.zee.admin.model.vo.SysMenuVO;
import com.zee.admin.service.ISysMenuService;
import com.zee.admin.service.ISysRoleMenuService;
import com.zee.admin.shiro.AdminUserDetail;
import com.zee.common.constant.Constant;
import com.zee.common.exception.ExceptionCast;
import com.zee.common.utils.ConvertUtil;
import com.zee.common.utils.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenu> implements ISysMenuService {
    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    @Override
    public SysMenuVO info(Integer id) {
        return baseMapper.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysMenuDTO dto) {
        SysMenu sysMenu = ConvertUtil.sourceToTarget(dto, SysMenu.class);

        //保存菜单
        this.save(sysMenu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysMenuDTO dto) {
        SysMenu sysMenu = ConvertUtil.sourceToTarget(dto, SysMenu.class);

        //上级菜单不能为自身
        if (sysMenu.getId().equals(sysMenu.getPid())) {
            ExceptionCast.cast(AdminCode.SUPERIOR_MENU_ERROR);
        }

        //更新菜单
        this.updateById(sysMenu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        //删除菜单
        this.removeById(id);

        //删除角色菜单关系
        sysRoleMenuService.deleteByMenuId(id);
    }

    @Override
    public List<SysMenuVO> getAllMenuList(Integer menuType) {
        List<SysMenuVO> menuList = baseMapper.getMenuList(menuType);

        return TreeUtil.build(menuList, Constant.MENU_ROOT);
    }

    @Override
    public List<SysMenuVO> getUserMenuList(AdminUserDetail user, Integer menuType) {
        List<SysMenuVO> menuList;

        //系统管理员，拥有最高权限
        if (user.getSuperAdmin() == SuperAdminEnum.YES.value()) {
            menuList = baseMapper.getMenuList(menuType);
        } else {
            menuList = baseMapper.getUserMenuList(user.getId(), menuType);
        }

        return TreeUtil.build(menuList);
    }

    @Override
    public List<SysMenu> getListPid(Integer pid) {
        return baseMapper.getListPid(pid);
    }

}